package utl.mofen.handler;

// {
//	   "fileInfo":
//	    {
//	       "id":"xxxxxx",      //接收id
//	       "file":"x.bmp",     //文件名 可以带相对路径
//	       "type":"rep",       //类型 
//         "action":1,         //删除
//	    }
//	}

import java.io.File;
import java.io.FileOutputStream;
import java.util.Hashtable;

import com.google.gson.JsonObject;

import utl.mofen.jsonStreamHandler.JSonStreamHandler;
import utl.mofen.utils.CRCUtil;
import utl.mofen.utils.FileUtil;
import utl.mofen.utils.GsonUtil;
import utl.mofen.utils.StringUtil;

public class FileOperaHandler extends JSonStreamHandler {
	private static int File_DELETE = 1;
	JsonObject jsonObject = null;
	
	String basePath = "E:\\cache\\";
	
	public void doAction() throws Exception {
		System.out.println("文件存放路径:" + basePath);
		jsonObject = this.jsonStream.getJSonObject();
		
		if (!jsonObject.has("fileInfo"))
		{
			jsonStream.clear();
			throw new Exception("缺少文件头信息!");
		}
		
		JsonObject fileInfo = jsonObject.get("fileInfo").getAsJsonObject();		
		if (!fileInfo.has("id"))
		{
			jsonStream.clear();
			throw new Exception("头信息缺少id!");
		}
		
		String id = fileInfo.get("id").getAsString();
		System.out.println(GsonUtil.json2String(fileInfo));
		
		if (!fileInfo.has("file"))
		{
			jsonStream.clear();
			throw new Exception("头信息缺少file(文件名)!");
		}
		String fileName = fileInfo.get("file").getAsString();
		
		String typeStr = "";
		if (fileInfo.has("type"))
		{
			typeStr = fileInfo.get("type").getAsString() + "\\";
		}
		
		String localFileName = basePath + typeStr + fileName;	
		
		if (!FileUtil.fileExists(localFileName))
		{
			this.jsonStream.setErrCode(1);
			throw new Exception("操作的文件不存在" + localFileName);
		}	
		
		if (!fileInfo.has("action"))
		{			
			throw new Exception("头信息缺少action(动作列表)!");
		}
		int __action = fileInfo.get("action").getAsInt();
		
		if (__action==File_DELETE)
		{
			FileUtil.deleteFile(localFileName);			
		}
	}
	
	public void setBasePath(String _basePath)
	{		
		if (StringUtil.stringIsNotEmpty(_basePath))
		{
			this.basePath = FileUtil.PathWithBackslash(_basePath);
		}
		
	}
	
	public String getBasePath()
	{
		return this.basePath;		
	}
}
